package com.xiaojie.filter;

import com.xiaojie.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * ClassNameJWTValidationFilter
 *
 * @Description Jwt验证过滤器
 * @Author yan
 * 2021/4/28 23:20
 * @Version 1.0
 **/
public class JWTValidationFilter extends BasicAuthenticationFilter {
    public JWTValidationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    public JWTValidationFilter(AuthenticationManager authenticationManager, AuthenticationEntryPoint authenticationEntryPoint) {
        super(authenticationManager, authenticationEntryPoint);
    }

    @Override
    /**
     * @Description:拦截请求，验证jwt
     * @Author: yan
     * @Date: 2021/4/28 23:42
     * @param request: 
     * @param response: 
     * @param chain: 
     * @return: void
     **/
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
       /* String token = request.getHeader("token");
        //jwt验证
        setAuthentication(token);*/
        SecurityContextHolder.getContext().setAuthentication
                (setAuthentication(request.getHeader("token")));
        super.doFilterInternal(request, response, chain);;
    }
    private UsernamePasswordAuthenticationToken setAuthentication(String token){
        String username = JwtUtil.getUsername(token);
        //验签
        if (StringUtils.isNotEmpty(username)){
            //解析权限列表
            List<SimpleGrantedAuthority> userRole = JwtUtil.getUserRole(token);
            return  new UsernamePasswordAuthenticationToken(username,null,userRole);
        }
        return null;
    }
}
